from fastapi import APIRouter, Query,UploadFile
from http import HTTPStatus
from dashscope import Application
from app.schemas.base import Success, SuccessExtra,Fail
ai_router = APIRouter()
import re

# 使用正则表达式替换URL
def replace_url(match):
    url = match.group(1)
    return f'<img src="{url}" style="width:225px;height:225px;border-radius: 10px;">'

# 匹配URL的正则表达式（兼容 ![]() 格式）
pattern = r'!\[\]\((http://[^\s]+)\)'

# 替换URL
def process_message(message):
    return re.sub(pattern, replace_url, message)

@ai_router.get("/chat", summary=f"对话")
async def do_chat(
        message: str = Query(None, description=f"消息"),
):
    response = Application.call(
        # 若没有配置环境变量，可用百炼API Key将下行替换为：api_key="sk-xxx"。但不建议在生产环境中直接将API Key硬编码到代码中，以减少API Key泄露风险。
        api_key="sk-643358641d2e4a2eb5143cde397fa33c",
        app_id='3097677ac66746d9bb91d6448f866356',  # 替换为实际的应用 ID
        prompt=message)

    if response.status_code != HTTPStatus.OK:
        print(f'request_id={response.request_id}')
        print(f'code={response.status_code}')
        print(f'message={response.message}')
        print(f'请参考文档：https://help.aliyun.com/zh/model-studio/developer-reference/error-code')
        return_message = "暂无相关信息哦"
    else:
        return_message = response.output.text
        return_message = process_message(return_message)

    return Success(data={"return_message":return_message})
